import _ from "lodash";
import fs from 'fs-extra';
import path from "path";
import { BaseTask, TaskResult } from "./BastTask.js";
import { toolchain } from "../../toolchain.js";
import { compareVersions } from "compare-versions";

export class WrapCSharpTask extends BaseTask {
    async run(): Promise<TaskResult<void>> {
        if (toolchain.option.engine != 'unity') {
            return { success: true, errorCode: 0 };
        }
        // 混合多个平台的必须wrap
        const sps = toolchain.params.projGlobalCfg?.support_platforms?.toLowerCase().split(/,\s*/);
        if (sps != null && sps.includes('webgl') && (sps.includes('pc') || sps.includes('android') || sps.includes('ios'))) {
            const wrapCopyFrom = path.join(toolchain.params.workSpacePath, 'WrapCopy');
            if (fs.existsSync(wrapCopyFrom)) {
                // 提前wrap出来的备份，直接拷贝，比如神将契约
                const copyFrom = path.join(wrapCopyFrom, toolchain.option.platform == 'WebGL' ? 'WebGL' : 'noneWebGL');
                const copyTo = path.join(toolchain.params.workSpacePath, 'Assets/Gen/Plugins/puerts_il2cpp');
                console.log(`copy wrapped native plugins from ${copyFrom} to ${copyTo}`);
                await fs.copy(copyFrom, copyTo, { overwrite: true });
            } else {
                // 没有提前wrap，则动态wrap
                // 第一个平台视为主平台，即不需要重新wrap
                if (this.cmdOption.platform.toLowerCase() != sps[0]) {
                    let wrapMethod = '';
                    // 支持在cfg.json里配置指定的wrap方法
                    const wrapMap = toolchain.params.projGlobalCfg?.wrap;
                    if (wrapMap != null) {
                        wrapMethod = wrapMap[toolchain.option.platform.toLowerCase()] ?? wrapMap['*'];
                    }
                    if (!wrapMethod) {
                        // 没有指定则根据puerts版本默认选择
                        const coreVer = toolchain.unity.getPuertsCoreVer();
                        if (compareVersions(coreVer, '2.0.0') >= 0) {
                            // 2.0.0之后使用GenV2
                            wrapMethod = 'Puerts.Editor.Generator.UnityMenu.GenV2';
                        } else {
                            wrapMethod = 'Puerts.Editor.Generator.UnityMenu.GenerateCode';
                        }
                    }
                    await toolchain.unity.runUnityCommand(this.cmdOption, ['-batchmode', '-projectPath', toolchain.params.workSpacePath, '-executeMethod', wrapMethod, '-quit'], 'Wrap C#', true);
                } else {
                    console.log('skip wrap csharp');
                }
            }
        } else {
            console.log('skip wrap csharp');
        }        

        return { success: true, errorCode: 0 };
    }

    get skip(): boolean {
        // 如果不重新打包则不需要重新wrap
        return !this.cmdOption.buildExe;
    }
}
